package com.web.exiaodao.remote.service.impl;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.FanliOrder;
import com.web.exiaodao.business.entity.FanliRules;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.business.repository.FanliFlowRepository;
import com.web.exiaodao.business.repository.FanliOrderRepository;
import com.web.exiaodao.business.repository.FanliRulesRepository;
import com.web.exiaodao.remote.service.ApiFanliOrderService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.service.ApiWalletTradeRecordService;
import com.web.exiaodao.remote.vo.FanliFlowVo;
import com.web.exiaodao.remote.vo.FanliOrderVo;
import com.web.exiaodao.remote.vo.UserVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: zhangl
 * @times: 2017-02-13 14:46:51
 * 类的说明：前端APIFanliOrder接口实现类
 **/
@Service("ApiFanliOrderService")
@Transactional(readOnly = false)
public class ApiFanliOrderServiceImpl extends BaseService<FanliOrder> implements ApiFanliOrderService{

	private static final Logger LOGGER = Logger.getLogger(ApiFanliOrderServiceImpl.class);

	@Autowired
	FanliOrderRepository fanliOrderRepository;

    @Autowired
    ApiUserService userService;

    @Autowired
    ApiWalletTradeRecordService walletTradeRecordService;
	
    @Autowired
    FanliFlowRepository fanliFlowRepository;
    
    @Autowired
    FanliRulesRepository fanliRulesRepository;
    
	@Override
	public XaResult<FanliOrderVo> findOne(Long tId) throws BusinessException {
		FanliOrder obj = fanliOrderRepository.findByIdAndStatusNot(tId,XaConstant.Status.delete);
		XaResult<FanliOrderVo> xr = new XaResult<FanliOrderVo>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj),FanliOrderVo.class));
			xr.getObject().setId(obj.getId());
			LOGGER.info("查询单个实体----->FanliOrder");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
			throw new BusinessException(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	@Override
	public XaResult<List<FanliOrderVo>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<FanliOrder> page = fanliOrderRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FanliOrder.class), pageable);
		XaResult<List<FanliOrderVo>> xr = new XaResult<List<FanliOrderVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), FanliOrderVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<List<FanliOrderVo>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<FanliOrder> page = fanliOrderRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), FanliOrder.class), pageable);
		XaResult<List<FanliOrderVo>> xr = new XaResult<List<FanliOrderVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), FanliOrderVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<FanliOrderVo> multiOperate(String modelIds,
			Integer status) throws BusinessException {
		XaResult<FanliOrderVo> xr = new XaResult<FanliOrderVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				FanliOrder obj = fanliOrderRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = fanliOrderRepository.save(obj);
					xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FanliOrderVo.class));
					xr.getObject().setId(obj.getId());
				}
			}
		}
		LOGGER.info("更改数据状态----->FanliOrder");
		return xr;
	}

	@Override
	public XaResult<FanliOrderVo> createModel(FanliOrder model)
			throws BusinessException {
		XaResult<FanliOrderVo> xr = new XaResult<FanliOrderVo>();
		FanliOrder obj = fanliOrderRepository.save(model);
		xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FanliOrderVo.class));
		xr.getObject().setId(obj.getId());
		LOGGER.info("新增数据成功----->FanliOrder");
		return xr;
	}

	@Override
	public XaResult<FanliOrderVo> updateModel(FanliOrder model)
			throws BusinessException {
		FanliOrder obj = fanliOrderRepository.findOne(model.getId());
		XaResult<FanliOrderVo> xr = new XaResult<FanliOrderVo>();
		if (XaUtil.isNotEmpty(obj)) {
					obj.setBusId(XaUtil.isNotEmpty(model.getBusId()) ? model.getBusId() : obj.getBusId());
					obj.setCreatOrderTime(XaUtil.isNotEmpty(model.getCreatOrderTime()) ? model.getCreatOrderTime() : obj.getCreatOrderTime());
					obj.setOrderMoney(XaUtil.isNotEmpty(model.getOrderMoney()) ? model.getOrderMoney() : obj.getOrderMoney());
					obj.setOrderNo(XaUtil.isNotEmpty(model.getOrderNo()) ? model.getOrderNo() : obj.getOrderNo());
					obj.setShopName(XaUtil.isNotEmpty(model.getShopName()) ? model.getShopName() : obj.getShopName());
					obj.setShopBrief(XaUtil.isNotEmpty(model.getShopBrief()) ? model.getShopBrief() : obj.getShopBrief());
					obj.setShopImg(XaUtil.isNotEmpty(model.getShopImg()) ? model.getShopImg() : obj.getShopImg());
					obj.setFanliMoney(XaUtil.isNotEmpty(model.getFanliMoney()) ? model.getFanliMoney() : obj.getFanliMoney());
					obj.setFaliTime(XaUtil.isNotEmpty(model.getFaliTime()) ? model.getFaliTime() : obj.getFaliTime());
					obj.setFaliOrderStatus(XaUtil.isNotEmpty(model.getFaliOrderStatus()) ? model.getFaliOrderStatus() : obj.getFaliOrderStatus());
					obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
					obj = fanliOrderRepository.save(obj);
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FanliOrderVo.class));
			xr.getObject().setId(obj.getId());
		} else {
			xr.error(XaConstant.Message.object_not_find);
		}
		LOGGER.info("编辑数据成功----->FanliOrder");
		return xr;
	}

	/**
	 * 根据临时返利订单生产返利对象
	 * @param temporder
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unused")
	@Override
	public XaResult<FanliOrderVo> createFanliOrder(FanliOrderVo.FanliTemporder temporder) throws BusinessException {
		XaResult<FanliOrderVo> xr = new XaResult<FanliOrderVo>();
		FanliOrder model = new FanliOrder();
		//1:根据ukey 查询 userid
		FanliFlowVo ffObj = fanliFlowRepository.findByExukeyAndStatusNot(temporder.getKey(), XaConstant.Status.delete);
		if(XaUtil.isNotEmpty(ffObj)){
			model.setUserId(XaUtil.isEmpty(ffObj.getUserId())?-1:ffObj.getUserId());
			model.setBusId(XaUtil.isEmpty(ffObj.getBusId())?-1:ffObj.getBusId());
		}else{
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		FanliRules frObj = fanliRulesRepository.findByBusIdAndStatusNot(ffObj.getBusId(), XaConstant.Status.delete);
		if(XaUtil.isNotEmpty(frObj)){
			Date d=new Date();   
			SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
			String nowDate = df.format(d);
			int day = Integer.parseInt(frObj.getFaliDays());
			String dayNew = df.format(new Date(d.getTime() + day * 24 * 60 * 60 * 1000));
			model.setFaliTime(dayNew);
			model.setPlatformFanliMoney(Double.valueOf(temporder.getOrderMoney())*Double.valueOf(frObj.getPlatformRaliRate()));
			model.setFanliMoney(Double.valueOf(temporder.getOrderMoney())*Double.valueOf(frObj.getUserFaliRate()));
		}else{
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		model.setFaliOrderStatus(Integer.valueOf(JConstant.FanliOrderStatus.RECENT_FANLI_ORDER).toString());
		model.setCreatOrderTime(temporder.getCreateOrderTime());
		model.setOrderMoney(temporder.getOrderMoney());
		model.setOrderNo(temporder.getOrderNo());
		model.setShopBrief(temporder.getShopBrief());
		model.setShopImg(temporder.getShopImg());
		model.setShopName(temporder.getShopName());
		
		//2:生产返利订单
		FanliOrder obj = fanliOrderRepository.save(model);
		xr.setObject(JSON.parseObject(JSON.toJSONString(obj), FanliOrderVo.class));
		xr.getObject().setId(obj.getId());
		LOGGER.info("新增数据成功----->FanliOrder");
		return xr;
	}

	/**
	 * @see JConstant.FanliStatus
	 * 返利结果处理
	 * @return
	 * @throws BusinessException
	 */
	@Override
	public XaResult<FanliOrderVo> fanliOrderSucess(String orderNo, String fanliStatus, String failFanliInfo, String failExpectedFanliTime) throws Exception {
		//1:查询返利订单
		//更新返利日期和返利状态
		UserVo userVo;
        FanliOrder fanliOrder = fanliOrderRepository.findByOrderNoAndStatusNot(orderNo, XaConstant.Status.delete);
        if (XaUtil.isNotEmpty(fanliOrder)) {
        	fanliOrder.setOrderNo(orderNo);
        	fanliOrder.setFaliTime(failExpectedFanliTime);
        	fanliOrder.setFaliOrderStatus(fanliStatus);
        	
        	//todo dz
        	userVo = userService.findOne(fanliOrder.getUserId()).getObject();
        }else{
        	throw new BusinessException(XaConstant.Message.object_not_find);
        }

        return walletTradeRecordService.fanliOrderSucess(fanliOrder, JSON.parseObject(JSON.toJSONString(userVo), User.class));
	}
}
